#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "commd.hpp"
using namespace std;

bool openfifo() {
    int res = mkfifo(FILENAME, 0666);
    if (res == 0) {
        cout << "create .fifo sucess" << endl;
        return true;
    }
    return false;
}

int main() {
start:
    // 打开fifo文件
    int fd = open(FILENAME, O_RDONLY);
    if (fd < 0) {
        if (openfifo()) {
            goto start;
        } else {
            return -1;
        }
    }
    cout << "open .fifo sucess…… read" << endl;

    // 读取.fifo文件
    while (true) {
        char buffer[1024];
        int n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0) {
            buffer[n] = '\0';
            cout << "client say:" << buffer << endl;
        } else {
            break;
        }
    }

    close(fd);
    cout << "close .fifo sucess……read" << endl;
    return 0;
}